package com.nnfe.fyd.view;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;

import java.util.ArrayList;
import java.util.List;

/**
 * ----------------------------------
 * Created by xyd on 2017/4/18.
 * <p/>
 * 描  述：
 * 广告循环播放的功能点列表：
 * 1. 添加banner
 * 2. 添加dot， 设置dot的两种状态背景，长宽高以及dot之间的距离
 * 3. 设置是否可以循环轮播
 * 4. 设置循环轮播的时间间隔
 * // ------
 * 5. reset
 * 6. 考虑无痛更换图片加载
 * <p>
 * 使用步骤：
 * <p>
 * <p/>
 * 修订历史:
 * ----------------------------------
 */
public class BannerView1 extends ViewPager {

    private Activity mContext;
    private ImageLoader imageLoader;
    private BannerViewAdapter bannerViewAdapter;
    private LinearLayout dotLinearLayout;
    private int SelectedRes, unSelectedRes, marginLeft, marginTop, marginRight, marginBottom;

    private int rollPeriod;
    private int bannerSize;
    private List<ImageView> viewList;

    private List<ImageView> indexViewList;

    private UrlListener listener;
    private OnItemClickLitener onItemClickLitener;

    boolean isLoop = true;
    private BannerHanlder bannerHanlder;
    private Message message;

    public BannerView1(Context context) {
        super(context);
    }

    public BannerView1(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    private void initBannerView(Builder builder) {

        this.dotLinearLayout = builder.dotLinearLayout;

        this.bannerSize = builder.bannerSize;
        this.onItemClickLitener = builder.onItemClickLitener;
        this.listener = builder.urlListener;

        this.rollPeriod = builder.rollPeriod;
        this.isLoop = builder.isLoop;

        // 初始化 imageloader
        initUIL();
        // 由传入的urlList生成 viewList
        initImageViewAndDotList();
        // 初始化 viewpager 的 adapter
        initAdapter();

    }

    //初始化Universal ImageLoader配置
    private void initUIL() {
        if (!ImageLoader.getInstance().isInited()) {
            ImageLoader.getInstance().init(ImageLoaderConfiguration.createDefault(mContext));
        }
        imageLoader = ImageLoader.getInstance();
    }


    private void initImageViewAndDotList() {

        // 准备viewList
        viewList = new ArrayList<>(bannerSize);

        if (viewList.size() > 0) {
            viewList.clear();
        }

        for (int i = 0; i <= bannerSize - 1; i++) {
            ImageView imageView = new ImageView(getContext());
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            viewList.add(imageView);
            //viewList.get(i).setImageDrawable(viewList.get(i).getDrawable());
            setBannerView(i);
        }


        // 添加滚动点
        if (indexViewList == null) {
            indexViewList = new ArrayList<>();
        }
        if (dotLinearLayout.getChildCount() > 0) {
            dotLinearLayout.removeAllViews();
        }

        for (int i = 0; i <= bannerSize - 1; i++) {
            ImageView imageView2 = new ImageView(getContext());
            if (i == 0) {
                imageView2.setImageResource(SelectedRes);
            } else {
                imageView2.setImageResource(unSelectedRes);
            }
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            params.setMargins(dpTppx(getContext(), marginLeft), dpTppx(getContext(), marginTop), dpTppx(getContext(), marginRight), dpTppx(getContext(), marginBottom));
            imageView2.setLayoutParams(params);
            indexViewList.add(imageView2);
            dotLinearLayout.addView(imageView2);
        }
        setOnpageChangeListener(SelectedRes, unSelectedRes);

    }

    private void setOnpageChangeListener(final int selectedRes, final int unSelectedRes) {
        addOnPageChangeListener(new OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                for (int i = 0; i < indexViewList.size(); i++) {
                    indexViewList.get(i).setImageResource(unSelectedRes);
                }
                indexViewList.get(position).setImageResource(selectedRes);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    private void setBannerView(final int i) {
        DisplayImageOptions options = new DisplayImageOptions.Builder()
                .cacheInMemory(true)
                .bitmapConfig(Bitmap.Config.RGB_565)
                .build();


        imageLoader.loadImage(listener.getImgUrl(i), options, new SimpleImageLoadingListener() {
            @Override
            public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                //设置图片和点击事件
                viewList.get(i).setImageBitmap(loadedImage);

                //setBannerOnClickListener(viewList, i);

                bannerViewAdapter.notifyDataSetChanged();

                Log.e("xyd", "加载url成功" + imageUri);

            }

        });
    }

    private void initAdapter() {
        bannerViewAdapter = new BannerViewAdapter(viewList);
        setAdapter(bannerViewAdapter);


    }

    private void setBannerOnClickListener(List<ImageView> viewList, final int index) {

        viewList.get(index).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!listener.getOnClickUrl(index % bannerSize).isEmpty()) {
                    //WebviewActivity01.launch(activity, "", listener.getOnClickUrl(index % bannerListSize), 1);
                }
            }
        });
    }

    @Override
    public void setCurrentItem(int item) {
        super.setCurrentItem(item);
        startAutoScroll();

    }

    // viewpager 可见状态变化的时候
    @Override
    protected void onVisibilityChanged(View changedView, int visibility) {
        super.onVisibilityChanged(changedView, visibility);
        if (visibility == VISIBLE) {
            startAutoScroll();
        } else {
            stopAutoScroll();
        }
    }

    private void startAutoScroll() {

        bannerHanlder = new BannerHanlder();

        message = Message.obtain();
        message.what = 0;
        bannerHanlder.sendMessageDelayed(message, rollPeriod);
    }

    private void stopAutoScroll() {
        if (message != null && message.what == 0) {
            Log.e("xyd", "不可见状态，抹除滚动");
            bannerHanlder.removeMessages(message.what);
        }
    }

    class BannerHanlder extends Handler {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0) {
                Log.e("xyd", "现在的item是： " + getCurrentItem());
                if (bannerSize - 1 == getCurrentItem()) {
                    setCurrentItem(0);
                } else {
                    setCurrentItem(getCurrentItem() + 1);
                }
            }
        }
    }


    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px
     */
    private static int dpTppx(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }


    /**
     * Buider
     * 所有参数均由Buider进行设置
     */
    public static final class Builder {

        private BannerView1 bannerView1;
        private LinearLayout dotLinearLayout;
        boolean isLoop = true;
        private int SelectedRes, unSelectedRes, marginLeft, marginTop, marginRight, marginBottom;
        private OnItemClickLitener onItemClickLitener;
        private UrlListener urlListener;

        int bannerSize = 1;
        int rollPeriod = 3000;

        public Builder(BannerView1 bannerView1) {
            this.bannerView1 = bannerView1;
        }


        public Builder bannerList(int imageSize) {
            this.bannerSize = imageSize;
            return this;
        }

        public Builder addDot(LinearLayout dotLinearLayout, int SelectedRes, int unSelectedRes,
                              int marginLeft, int marginTop, int marginRight, int marginBottom) {
            this.dotLinearLayout = dotLinearLayout;
            this.SelectedRes = SelectedRes;
            this.unSelectedRes = unSelectedRes;
            this.marginLeft = marginLeft;
            this.marginTop = marginTop;
            this.marginRight = marginRight;
            this.marginBottom = marginBottom;
            return this;
        }

        /**
         * 设置滚动时间间隔
         *
         * @param rollPeriod
         * @return
         */
        public Builder setRollPeriod(int rollPeriod) {
            this.rollPeriod = rollPeriod;
            return this;
        }

        /**
         * @param isLoop 设置是否循环滚动
         */
        public Builder isLoop(boolean isLoop) {
            this.isLoop = isLoop;
            return this;
        }

        public Builder addOnItemClickListener(OnItemClickLitener onItemClickLitener) {
            this.onItemClickLitener = onItemClickLitener;
            return this;
        }

        public Builder addUrlListener(UrlListener urlListener) {
            this.urlListener = urlListener;
            return this;
        }

        public BannerView1 build() {
            bannerView1.initBannerView(this);
            return bannerView1;
        }

    }

    //根据list数据长度自动生成的默认Adapter
    public class BannerViewAdapter extends PagerAdapter {

        List<ImageView> viewList;


        public BannerViewAdapter(List<ImageView> viewList) {
            this.viewList = viewList;
        }


        @Override
        public int getItemPosition(Object object) {
            return POSITION_NONE;
        }

        @Override
        public int getCount() {
            return bannerSize;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            View view = viewList.get(position % (viewList.size()));
            ViewGroup parent = (ViewGroup) view.getParent();
            if (parent != null) {
                parent.removeView(view);
            }
            container.addView(view);
            return view;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            View view = viewList.get(position % (viewList.size()));
            container.removeView(view);
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

    }


    public interface UrlListener {
        String getImgUrl(int position);

        String getOnClickUrl(int position);
    }

    public interface OnItemClickLitener {
        void onClick(int position, String clickUrl);
    }

}